import moment from 'moment';
import ToolTips from '../components/ToolTips';

export const CONSTANT_TAB_KEY1 = 'adjustment'; // 调整版
export const CONSTANT_TAB_KEY2 = 'practical'; // 实际版
export const CONSTANT_TAB_KEY3 = 'investOfficial'; // 投资正式版
export const CONSTANT_TAB_KEY4 = 'ability'; // 能力版
export const CONSTANT_TAB_KEY5 = 'dynamic'; // 动态版
export const CONSTANT_TAB_KEY6 = 'investment'; // 投资版

// 项目回款分析表
const versionMap = {
  [CONSTANT_TAB_KEY1]: '调整版',
  [CONSTANT_TAB_KEY2]: '实际版',
  [CONSTANT_TAB_KEY3]: '投资正式版',
};

// 投资回款承诺（能力）分析表
const columnsMap = {
  [CONSTANT_TAB_KEY6]: '投资版回款',
  [CONSTANT_TAB_KEY5]: '动态版回款',
  [CONSTANT_TAB_KEY4]: '能力版回款',
};

// 浮点倍数，浮点系数
export const FLOAT_MODULUS_NUM = 1000;
export const FLOAT_MODULUS = 3;

// 转为3位小数
const resetNum = val => {
  if (val === '-') return val;
  if (isNaN(val)) return '0.000';
  return `${(val * 100).toFixed(FLOAT_MODULUS)}`;
};
// 根据数值正负 return 不同颜色
const colorDiv = val => {
  const num = Number(val);
  if (num > 0) return <span className="color-green">+{val}%</span>;
  if (num < 0) return <span className="color-red">{val}%</span>;
  if (num == 0) return <span>{val}%</span>;
  return (
    <div style={{ width: 64 }} className="tcenter">
      {val}
    </div>
  );
};
// 区分百分数和 '-'
const numDiv = val => {
  if (!isNaN(val)) return `${val}%`;
  return (
    <div style={{ width: 64 }} className="tcenter">
      {val}
    </div>
  );
};

// 回款计划 return 不同颜色
const colorSpan = num => {
  if (num > 0) return <span className="color-green">+{num}</span>;
  if (num < 0) return <span className="color-red">{num}</span>;
  if (isNaN(num)) {
    return (
      <div style={{ width: 124 }} className="tcenter">
        {num}
      </div>
    );
  }
  return num;
};
// 回款计划 return num || '-'
const numSpan = num => {
  if (!isNaN(num)) return num;
  return (
    <div style={{ width: 124 }} className="tcenter">
      {num}
    </div>
  );
};
// 元=>万元（保留四位小数）
const resetSpanNum = num => {
  if (isNaN(num)) return num;
  return (num / 10000).toFixed(4);
};

// 0~24 月 字段与名称对应
export const monthName = {
  oneMonth: '第1个月',
  twoMonth: '第2个月',
  threeMonth: '第3个月',
  fourMonth: '第4个月',
  fiveMonth: '第5个月',
  sixMonth: '第6个月',
  sevenMonth: '第7个月',
  eightMonth: '第8个月',
  nineMonth: '第9个月',
  tenMonth: '第10个月',
  elevenMonth: '第11个月',
  twelveMonth: '第12个月',
  thirteenMonth: '第13个月',
  fourteenMonth: '第14个月',
  fifteenMonth: '第15个月',
  sixteenMonth: '第16个月',
  seventeenMonth: '第17个月',
  eighteenMonth: '第18个月',
  nineteenMonth: '第19个月',
  twentyMonth: '第20个月',
  twentyOneMonth: '第21个月',
  twentyTwoMonth: '第22个月',
  twentyThreeMonth: '第23个月',
  twentyFourMonth: '第24个月',
};
// monthName 所有 key 的 arr
export const monthKeys = Object.keys(monthName);
// 12 个业态 + 4 大业态 key=>value
export const productType = {
  101: {
    name: '住宅',
    unfold: true,
  },
  102: {
    name: '商业',
  },
  103: {
    name: '车位',
    unfold: true,
  },
  105: {
    name: '其他',
  },
  '013': {
    name: '住宅',
    parent: '101',
    unfold: true,
  },
  '044': {
    name: 'LOFT',
    parent: '102',
  },
  '053': {
    name: '商业',
    parent: '102',
  },
  '059': {
    name: '标准办公',
    parent: '102',
  },
  100: {
    name: '酒店式公寓',
    parent: '102',
  },
  104: {
    name: '商墅',
    parent: '102',
  },
  108: {
    name: '独栋办公',
    parent: '102',
  },
  132: {
    name: '配套',
    parent: '105',
  },
  135: {
    name: '酒店',
    parent: '102',
  },
  139: {
    name: '车位',
    parent: '103',
    unfold: true,
  },
  146: {
    name: '地下储藏室/非机动车库',
    parent: '105',
  },
  '089': {
    name: '其他',
    parent: '105',
  },
};
// 12 个业态的 key
export const productTypeKeys = Object.keys(productType);

// resetCityData 使用
const arrToObj = (obj, data) => {
  monthKeys.map((month, monthIndex) => {
    obj[month] = resetNum(data[month]);
  });
};

// 项目回款系数分析表reset 数据
export const resetProjectData = (res, { versionType, vsVersionType }) => {
  const columns = [
    {
      key: 'projectName',
      dataKey: 'projectName',
      width: 200,
      frozen: 'left',
      // headerRenderer: ({ headerIndex, column, columnIndex }) => {},
      // rowData行数据
      dataGetter: ({ rowData, rowIndex, column, columnIndex }) => (
        <ToolTips data={rowData.projectName} />
      ),
      // cellRenderer: record => {}
    },
    {
      key: 'proProductType',
      dataKey: 'proProductType',
      width: 100,
      frozen: 'left',
      align: 'center',
      dataGetter: ({ rowData }) => <ToolTips data={rowData.proProductType} />,
    },
  ];
  const headerRenderer = [
    {
      name: '项目名称',
      key: 'projectName',
      rowspan: 2,
      colspan: 1,
    },
    {
      name: '标准业态',
      key: 'proProductType',
      rowspan: 2,
      colspan: 1,
    },
  ];
  const data = [];
  // 设置合并数量
  let cityProjectName = '';
  let cityProjectIndex = 0;
  // tar => 城市
  res.map((city, cityIndex) => {
    // 单位 data
    const unit = {
      id: `dataKey_${cityIndex + 1}`,
      key: `dataKey_${cityIndex + 1}`,
      projectName: city.projectName,
      proProductType: city.proProductType,
    };
    if (city.projectName !== cityProjectName) {
      unit.rowSpan = 1;
      cityProjectName = city.projectName;
      cityProjectIndex = cityIndex;
    } else {
      data[cityProjectIndex].rowSpan += 1;
    }
    // 月份 （对比，对比，差异）
    city.vsList.map((month, monthIndex) => {
      // 声明月份
      const monthNum = month.num || monthIndex + 1;
      // 只取第一个城市信息设计表头
      if (cityIndex === 0) {
        //
        headerRenderer.push({
          name: `第${monthNum}个月`,
          key: `month_${monthNum}`,
          rowspan: 1,
          colspan: 3,
          children: [
            {
              name: versionMap[versionType],
              key: `compare_${monthNum}`,
              colspan: 1,
            },
            {
              name: versionMap[vsVersionType],
              key: `beCompared_${monthNum}`,
              colspan: 1,
            },
            {
              name: '差异',
              key: `difference_${monthNum}`,
              colspan: 1,
            },
          ],
        });
        //
        columns.push(
          {
            key: `compare_${monthNum}_columns`,
            dataKey: `compare_${monthNum}`,
            width: 80,
            align: 'right',
            dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
              numDiv(rowData[`compare_${monthNum}`]),
          },
          {
            key: `beCompared_${monthNum}_columns`,
            dataKey: `beCompared_${monthNum}`,
            width: 80,
            align: 'right',
            dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
              numDiv(rowData[`beCompared_${monthNum}`]),
          },
          {
            key: `difference_${monthNum}_columns`,
            dataKey: `difference_${monthNum}`,
            width: 80,
            align: 'right',
            dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
              colorDiv(rowData[`difference_${monthNum}`]),
          },
        );
      }
      //
      unit[`compare_${monthNum}`] = resetNum(month.compare);
      unit[`beCompared_${monthNum}`] = resetNum(month.beCompared);
      unit[`difference_${monthNum}`] = resetNum(month.difference);
    });
    data.push(unit);
  });
  return {
    headerRenderer,
    columns,
    data,
    code: 1,
  };
};

// 城市回款系数分析表reset 数据
export const resetCityData = res => {
  // 可展开的 key list
  const columns = [
    {
      key: 'cityName',
      dataKey: 'cityName',
      width: 100,
      rowSpan: 2,
      frozen: 'left',
      // headerRenderer: ({ headerIndex, column, columnIndex }) => {},
      // rowData行数据
      dataGetter: ({ rowData, rowIndex, column, columnIndex }) => (
        <ToolTips data={rowData.cityName} />
      ),
      // cellRenderer: record => {}
    },
    {
      key: 'productType',
      dataKey: 'productType',
      width: 200,
      frozen: 'left',
      dataGetter: ({ rowData }) => <ToolTips data={rowData.productType} />,
    },
  ];
  const headerRenderer = [
    {
      name: '城市',
      key: 'cityName',
      rowspan: 1,
      colspan: 1,
    },
    {
      name: '标准业态',
      key: 'productCode',
      rowspan: 1,
      colspan: 1,
    },
  ];
  const data = [];

  monthKeys.map(month => {
    columns.push({
      key: `key_${month}`,
      dataKey: month,
      width: 100,
      align: 'right',
      dataGetter: ({ rowData, rowIndex, column, columnIndex }) => numDiv(rowData[month]),
    });
    headerRenderer.push({
      name: monthName[month],
      key: month,
      rowspan: 1,
      colspan: 1,
    });
  });
  // tar => 城市
  res.map((city, cityIndex) => {
    // 月份 （对比，对比，差异）
    const cityData = [];
    let cityDataChildrenLength = 0;
    city.list.map((product, productIndex) => {
      // 找到业态
      const { name, parent, unfold } = productType[product.code];
      // 此条数据业态是父级业态数据
      if (!parent) {
        // 接口排序问题，可能先处理子数据后处理了父级数据，所以判断是否创建了没有数据的父级
        const parentIndex = cityData.findIndex(tar => tar.id === `${cityIndex}_${product.code}`);
        // 存在无数据的父级
        if (parentIndex !== -1 && !unfold) {
          arrToObj(cityData[parentIndex], product.dmCityReturnCoefficient);
        }
        // 不存在父级
        if (parentIndex === -1 && !unfold) {
          // 父级业态
          const parentData = {
            pid: cityIndex,
            id: `${cityIndex}_${product.code}`,
            key: `parent_${cityIndex + 1}_${product.code}`, // parent_1_102
            // cityName: city.cityName,
            productType: name,
            children: [],
          };
          arrToObj(parentData, product.dmCityReturnCoefficient);
          cityData.push(parentData);
        }
      }
      // 此条数据是子级业态数据
      if (parent) {
        // 所对应父级业态是 parent
        // 找到父级位置
        const parentIndex = cityData.findIndex(tar => tar.id === `${cityIndex}_${parent}`);
        // 已创建父级
        if (parentIndex !== -1) {
          const childData = {
            id: `${cityIndex}_${parent}_${product.code}`,
            pid: `${cityIndex}_${parent}`, // city 下标+ 父级业态 code
            key: `child_${cityIndex + 1}_${product.code}`, // child_1_102
            // cityName: city.cityName,
            productType: name,
          };
          arrToObj(childData, product.dmCityReturnCoefficient);
          cityData[parentIndex].children.push(childData);
          cityDataChildrenLength += 1;
        }
        // 未创建父级 创建子级和父级
        if (parentIndex === -1 && !unfold) {
          // 创建子级数据
          const childData = {
            id: `${cityIndex}_${parent}_${product.code}`,
            pid: `${cityIndex}_${parent}`,
            key: `child_${cityIndex + 1}_${product.code}`,
            // cityName: city.cityName,
            productType: name,
          };
          arrToObj(childData, product.dmCityReturnCoefficient);
          // 创建无数据父级
          const parentData = {
            pid: cityIndex,
            id: `${cityIndex}_${parent}`,
            key: `parent_${cityIndex + 1}_${parent}`,
            // cityName: city.cityName,
            productType: productType[parent].name,
            children: [childData],
          };
          cityData.push(parentData);
          cityDataChildrenLength += 1;
        }
        // 不存在父级（住宅，车位）
        if (parentIndex === -1 && unfold) {
          const parentData = {
            pid: cityIndex,
            id: `${cityIndex}_${parent}`,
            key: `parent_${cityIndex + 1}_${parent}`,
            // cityName: city.cityName,
            productType: productType[parent].name,
          };
          arrToObj(parentData, product.dmCityReturnCoefficient);
          cityData.push(parentData);
        }
      }
    });

    const newCityData = cityData.map((tar, index) => {
      if (index === 0) {
        return {
          ...tar,
          cityName: city.cityName,
          minRowNum: cityData.length, // 最小为大业态数量
          maxRowNum: cityData.length + cityDataChildrenLength, // 最大为大业态+小业态数量
          rowSpan: cityData.length,
        };
      }
      return {
        ...tar,
      };
    });

    data.push.apply(data, newCityData);
  });
  return {
    columns,
    headerRenderer,
    data,
    code: 1,
  };
};

// 投资回款承诺（能力）reset 数据
export const resetPromiseOrAbilityData = (res, { versionType, vsVersionType, yearMonth }) => {
  const historyYear = moment(yearMonth)
    .subtract(1, 'years')
    .format('YYYY');
  const nowyear = moment(yearMonth).format('YYYY');
  // 季度
  const quarterArr = ['一', '二', '三', '四'];
  const exportData = {
    columns: [
      {
        key: 'projectName',
        dataKey: 'projectName',
        width: 200,
        frozen: 'left',
        // headerRenderer: ({ headerIndex, column, columnIndex }) => {},
        // rowData行数据
        dataGetter: ({ rowData, rowIndex, column, columnIndex }) => (
          <ToolTips data={rowData.projectName} />
        ),
        // cellRenderer: record => {}
      },
      {
        key: 'proProductType',
        dataKey: 'proProductType',
        width: 100,
        frozen: 'left',
        align: 'center',
        dataGetter: ({ rowData }) => <ToolTips data={rowData.proProductType} />,
      },
    ],
    headerRenderer: [
      {
        name: '项目名称',
        key: 'projectName',
        rowspan: 2,
        colspan: 1,
      },
      {
        name: '标准业态',
        key: 'productCode',
        rowspan: 2,
        colspan: 1,
      },
    ],
    data: [],
    code: 1,
  };
  if (!res) return exportData;
  // 设置合并数量
  let cityProjectName = '';
  let cityProjectIndex = 0;
  // city => 城市
  res.map(
    ({ history, future, vsMonthList, vsQuarterList, proProductType, projectName }, cityIndex) => {
      // 单位 data
      const unit = {
        key: `dataKey_${cityIndex + 1}`,
        id: `dataKey_${cityIndex + 1}`,
        projectName,
        proProductType,
      };
      if (projectName !== cityProjectName) {
        unit.rowSpan = 1;
        cityProjectName = projectName;
        cityProjectIndex = cityIndex;
      } else {
        exportData.data[cityProjectIndex].rowSpan += 1;
      }
      // 历史
      if (history) {
        if (cityIndex === 0) {
          exportData.columns.push(
            {
              key: 'compare_history_columns',
              dataKey: 'compare_history',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                numSpan(rowData.compare_history),
            },
            {
              key: 'beCompared_history_columns',
              dataKey: 'beCompared_history',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                numSpan(rowData.beCompared_history),
            },
            {
              key: 'difference_history_columns',
              dataKey: 'difference_history',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                colorSpan(rowData.difference_history),
            },
          );
          exportData.headerRenderer.push({
            name: `${historyYear}年及以前汇总`,
            key: 'month_history',
            rowspan: 1,
            colspan: 3,
            children: [
              {
                name: `${columnsMap[versionType]}(万元)`,
                key: 'compare_history',
                colspan: 1,
              },
              {
                name: `${columnsMap[vsVersionType]}(万元)`,
                key: 'beCompared_history',
                colspan: 1,
              },
              {
                name: '差异(万元)',
                key: 'difference_history',
                colspan: 1,
              },
            ],
          });
        }
        unit.compare_history = resetSpanNum(history.compare);
        unit.beCompared_history = resetSpanNum(history.beCompared);
        unit.difference_history = resetSpanNum(history.difference);
      }
      // 12 个月
      if (vsMonthList && vsMonthList.length > 0) {
        vsMonthList.map((month, monthIndex) => {
          const monthNum = monthIndex + 1;
          if (cityIndex === 0) {
            const monthNumber = (monthIndex % 12) + 1;
            const monthYear = moment(yearMonth)
              .add(parseInt(monthIndex / 12), 'years')
              .format('YYYY');
            exportData.columns.push(
              {
                key: `compare_${monthNum}_columns`,
                dataKey: `compare_${monthNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  numSpan(rowData[`compare_${monthNum}`]),
              },
              {
                key: `beCompared_${monthNum}_columns`,
                dataKey: `beCompared_${monthNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  numSpan(rowData[`beCompared_${monthNum}`]),
              },
              {
                key: `difference_${monthNum}_columns`,
                dataKey: `difference_${monthNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  colorSpan(rowData[`difference_${monthNum}`]),
              },
            );
            exportData.headerRenderer.push({
              name: `${monthYear}年${monthNumber}月`,
              key: `month_${monthNum}`,
              rowspan: 1,
              colspan: 3,
              children: [
                {
                  name: `${columnsMap[versionType]}(万元)`,
                  key: `compare_${monthNum}`,
                  colspan: 1,
                },
                {
                  name: `${columnsMap[vsVersionType]}(万元)`,
                  key: `beCompared_${monthNum}`,
                  colspan: 1,
                },
                {
                  name: '差异(万元)',
                  key: `difference_${monthNum}`,
                  colspan: 1,
                },
              ],
            });
          }
          unit[`compare_${monthNum}`] = resetSpanNum(month.compare);
          unit[`beCompared_${monthNum}`] = resetSpanNum(month.beCompared);
          unit[`difference_${monthNum}`] = resetSpanNum(month.difference);
        });
      }
      // 季度
      if (vsQuarterList && vsQuarterList.length > 0) {
        const addYear = vsMonthList ? parseInt(vsMonthList.length / 12) : 3;
        vsQuarterList.map((quarter, quarterIndex) => {
          const quarterNum = quarterIndex + 1; // 季度
          if (cityIndex === 0) {
            const quarterNumber = quarterIndex % 4;
            const querterYear = moment(yearMonth)
              .add(parseInt(quarterIndex / 4 + addYear), 'years')
              .format('YYYY');
            exportData.columns.push(
              {
                key: `compare_quarter${quarterNum}_columns`,
                dataKey: `compare_quarter${quarterNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  numSpan(rowData[`compare_quarter${quarterNum}`]),
              },
              {
                key: `beCompared_quarter${quarterNum}_columns`,
                dataKey: `beCompared_quarter${quarterNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  numSpan(rowData[`beCompared_quarter${quarterNum}`]),
              },
              {
                key: `difference_quarter${quarterNum}_columns`,
                dataKey: `difference_quarter${quarterNum}`,
                width: 140,
                align: 'right',
                dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                  colorSpan(rowData[`difference_quarter${quarterNum}`]),
              },
            );
            exportData.headerRenderer.push({
              name: `${querterYear}年${quarterArr[quarterNumber]}季度`,
              key: `quarter_${quarterNum}`,
              rowspan: 1,
              colspan: 3,
              children: [
                {
                  name: `${columnsMap[versionType]}(万元)`,
                  key: `compare_quarter${quarterNum}`,
                  colspan: 1,
                },
                {
                  name: `${columnsMap[vsVersionType]}(万元)`,
                  key: `beCompared_quarter${quarterNum}`,
                  colspan: 1,
                },
                {
                  name: '差异(万元)',
                  key: `difference_quarter${quarterNum}`,
                  colspan: 1,
                },
              ],
            });
          }
          unit[`compare_quarter${quarterNum}`] = resetSpanNum(quarter.compare);
          unit[`beCompared_quarter${quarterNum}`] = resetSpanNum(quarter.beCompared);
          unit[`difference_quarter${quarterNum}`] = resetSpanNum(quarter.difference);
        });
      }
      // 未来
      if (future) {
        // vsMonthList总长度 / 12个月  vsQuarterList总长度 / 4个季度
        const totalYear = vsMonthList.length / 12 + vsQuarterList.length / 4;
        const futureYear = moment(yearMonth)
          .add(totalYear, 'years')
          .format('YYYY');
        if (cityIndex === 0) {
          exportData.columns.push(
            {
              key: 'compare_future_columns',
              dataKey: 'compare_future',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                numSpan(rowData.compare_future),
            },
            {
              key: 'beCompared_future_columns',
              dataKey: 'beCompared_future',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                numSpan(rowData.beCompared_future),
            },
            {
              key: 'difference_future_columns',
              dataKey: 'difference_future',
              width: 140,
              align: 'right',
              dataGetter: ({ rowData, rowIndex, column, columnIndex }) =>
                colorSpan(rowData.difference_future),
            },
          );
          exportData.headerRenderer.push({
            name: `${futureYear}年及以后汇总`,
            key: 'month_future',
            rowspan: 1,
            colspan: 3,
            children: [
              {
                name: `${columnsMap[versionType]}(万元)`,
                key: 'compare_future',
                colspan: 1,
              },
              {
                name: `${columnsMap[vsVersionType]}(万元)`,
                key: 'beCompared_future',
                colspan: 1,
              },
              {
                name: '差异(万元)',
                key: 'difference_future',
                colspan: 1,
              },
            ],
          });
        }
        unit.compare_future = resetSpanNum(future.compare);
        unit.beCompared_future = resetSpanNum(future.beCompared);
        unit.difference_future = resetSpanNum(future.difference);
      }
      exportData.data.push(unit);
    },
  );
  return exportData;
};
